package com.itheima.controller;

import com.itheima.common.CommonResult;
import com.itheima.common.PageInfo;
import com.itheima.pojo.Employee;
import com.itheima.service.EmploeeService;
import com.itheima.vo.EmployeeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
//跨域请求的一种方式 不行
// @CrossOrigin
@RestController
@RequestMapping("/employee")
public class ReggieController {
    @Autowired
    private EmploeeService emploeeService;
    @PostMapping("/login")
    public CommonResult login(@RequestBody Employee employee){
        EmployeeVo emp = emploeeService.login(employee.getUsername(), employee.getPassword());
        if (emp==null){
            return CommonResult.error("用户名密码错误");
        }
        return CommonResult.success(emp);
    };
    @GetMapping
    public CommonResult getEmployee(){
        return CommonResult.success("访问成功");
    }
    @PostMapping("/logout")
    public  CommonResult logout(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        emploeeService.clearToken(token);
        return CommonResult.success("退出登录成功");
    }
    //新增员工
    @PostMapping
    public CommonResult save(@RequestBody Employee employee){
        // System.out.println(employee);
        boolean addemployee = emploeeService.save(employee);
        return CommonResult.success(addemployee);
    }

    @GetMapping("/{id}")
    public CommonResult getById(@PathVariable("id") String id){
        EmployeeVo byId = emploeeService.getById(id);

        return CommonResult.success(byId);
    }
    //@RequestParam("page") 默认是有的  请求参数  defaultValue = "1"  默认值是1
    @GetMapping("/page")
    public CommonResult page(String name,
                             @RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer pageSize){
        PageInfo<Employee> pageInfo = emploeeService.page(name, page, pageSize);
        return CommonResult.success(pageInfo);
    }
    //修改员工
   @PutMapping
    public CommonResult update(@RequestBody Employee employee){
       boolean upd = emploeeService.update(employee);
       return CommonResult.success("员工信息修改成功");

   }
}
